local thbattle__qiurangzi_shanggong = fk.CreateSkill {

  name = "thbattle__qiurangzi_shanggong",

  tags = { Skill.Compulsory, },

}



thbattle__qiurangzi_shanggong:addEffect(fk.AfterCardsMove, {
  name = "thbattle__qiurangzi_shanggong",
  anim_type = "drawcard",
  can_trigger = function(self, event, target, player, data)
    if player:hasSkill(thbattle__qiurangzi_shanggong.name) then
      local e = player.room.logic:getCurrentEvent().parent
      if e and e.event == GameEvent.UseCard then
        local use = e.data
        if use.card.trueName == "amazing_grace" then
          local ids = {}
          for _, move in ipairs(data) do
            if move.toArea == Card.DiscardPile and move.moveReason == fk.ReasonPutIntoDiscardPile then
              for _, info in ipairs(move.moveInfo) do
                if player.room:getCardArea(info.cardId) == Card.DiscardPile then
                  table.insertIfNeed(ids, info.cardId)
                end
              end
            end
          end
          if #ids > 0 then
            event:setCostData(self, ids)
            return true
          end
        end
      end
    end
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local to = player.room:askForChoosePlayers(player, table.map(player.room:getAlivePlayers(), Util.IdMapper), 1, 1,
      "#thbattle__qiurangzi_shanggong-choose", thbattle__qiurangzi_shanggong.name, false)
    room:obtainCard(room:getPlayerById(to[1]), event:getCostData(self), true, fk.ReasonJustMove,
      room:getPlayerById(to[1]),
      thbattle__qiurangzi_shanggong.name, "@@thb_mingpai")
  end,
})

thbattle__qiurangzi_shanggong:addEffect(fk.BeforeCardUseEffect, {
  name = "#thbattle__qiurangzi_shanggong_trigger",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(thbattle__qiurangzi_shanggong.name) and data.card and data.card.trueName == "amazing_grace"
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local first, last = {}, {}
    for _, info in ipairs(data.tos) do
      if info:hasSkill(self) then
        table.insert(first, info)
      else
        table.insert(last, info)
      end
    end
    data.tos = table.connect(first, last)
  end,
})

return thbattle__qiurangzi_shanggong
